package simplehdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;


/**
* @Author : liqiang
* @Date : 2021/3/13 11:04
* @Description : 查看某个文件在HDFS集群中的位置
**/
public class WhereFile {

    public static void main(String[] args) throws IOException {
        String des = "hdfs://node01:8020/test.txt";
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(des),conf);
        Path file = new Path(des);
        //创建FileStatus对象
        FileStatus fileStatus = fs.getFileStatus(file);

        //创建一个BlockLocation数组对象，调用getFileBlockLocations
        BlockLocation[] blockLocations = fs.getFileBlockLocations(fileStatus,0,fileStatus.getLen());

        int blockLen = blockLocations.length;
        for(int i = 0;i < blockLen;++i){
            String[] hosts = blockLocations[i].getHosts();
            System.out.println("blockID:"+i+"\n"+"location:"+hosts[0]+" "+hosts[1]+" "+hosts[2]);
        }
    }
}
